package com.im.app.controller;

import com.im.app.authConfig.CurrentUser;
import com.im.app.authConfig.RequireLogin;
import com.im.app.manager.ConversationManager;
import com.im.app.manager.UserManager;
import com.im.app.model.Conversations;
import com.im.app.model.User;
import com.im.app.service.ChatLogsService;
import com.im.app.service.ConversationsService;
import com.im.app.service.IUserService;
import com.im.app.utils.IpToAddressUtil;
import com.im.app.utils.Response;
import com.im.app.utils.ResponseResult;
import org.jim.core.ImChannelContext;
import org.jim.core.ImPacket;
import org.jim.core.cache.redis.JedisTemplate;
import org.jim.core.packets.Command;
import org.jim.core.packets.RespBody;
import org.jim.server.JimServerAPI;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;


@RestController
@RequestMapping(value = "/user")
public class IMUserController {

    @Resource
    private IUserService userService;

    @Resource
    private ConversationsService conversationsService;

    @Resource
    private ChatLogsService chatLogsService;


    /**
     * 查询个人信息
     *
     * @author aaa
     * @date 2023-04-12
     */
    @RequireLogin
    @GetMapping("/getUserInfo")
    public ResponseResult<Object> getUserInfo(@CurrentUser User user, String userId){
        User user1 = null;
        if (userId == null){
            user1 = userService.getUserByUserId(user.getUserId());
            if (user1 != null){
                if (user1.getStatus() == 0){
                    List<ImChannelContext> channelContexts = JimServerAPI.getByUserId(user.getUserId());
                    for (ImChannelContext channelContext: channelContexts) {
                        JimServerAPI.remove(channelContext,"当前用户已禁用");
                        String token1 = channelContext.getSessionContext().getImClientNode().getUser().getToken();
                        try {
                            JedisTemplate.me().delKey(token1);
                        } catch (Exception e) {
                            throw new RuntimeException(e);
                        }
                    }
                    return Response.makeRsp(401,"当前用户已禁用");
                }
            }
        }else {
            user1 = userService.getUserByUserId(userId);
        }
        if(user1 != null){
            return Response.makeOKRsp(user1);
        }else {
            return Response.makeErrRsp("没有对应用户");
        }
    }

    /**
     * 修改个人信息
     *
     * @author aaa
     * @date 2023-04-12
     */
    @RequireLogin
    @PostMapping("/updateUserInfo")
    public ResponseResult<Object> updateUserInfo(@CurrentUser User user,@RequestBody User newUser){
        if(user==null){
            return Response.makeErrRsp("参数异常");
        }
        if(newUser.getAvatar() == null){
            return Response.makeErrRsp("头像不能为空");
        }
        if(newUser.getName() == null){
            return Response.makeErrRsp("昵称不能为空");
        }
        newUser.setUserId(user.getUserId());
        //设置启用状态
        newUser.setStatus(1);
        boolean update = userService.updateById(newUser);
        if(update){
            chatLogsService.updateMsg(newUser.getUserId(),newUser.getName(),newUser.getAvatar());
            conversationsService.updateCon(newUser.getUserId(),newUser.getName(),newUser.getAvatar());
            User user1 = userService.getUserByUserId(user.getUserId());
            String key = "kefu_"+user.getUserId();
            UserManager.getManager().cacheKefuUser(key,user1);
        }

        return Response.makeOKRsp("修改成功").setData(user);
    }


    @RequireLogin
    @PostMapping("/updateSecurityUrlType")
    public ResponseResult<Object> updateSecurityUrlType(@CurrentUser User user, int type){
        if(user==null){
            return Response.makeErrRsp("参数异常");
        }
        user.setStatus(1);
        user.setSecurityUrl(type);
        userService.updateById(user);
        return Response.makeOKRsp("修改成功").setData(user);
    }


    @RequireLogin
    @PostMapping("/updateIsNotice")
    public ResponseResult<Object> updateIsNotice(@CurrentUser User user, int isNotice){
        if(user==null){
            return Response.makeErrRsp("参数异常");
        }
        //设置启用状态
        user.setStatus(1);
        user.setIsNotice(isNotice);
        boolean update = userService.updateById(user);
        if(update){
            String key = "kefu_"+user.getUserId();
            UserManager.getManager().cacheKefuUser(key,user);
        }
        return Response.makeOKRsp("修改成功").setData(user);
    }

    @RequireLogin
    @PostMapping("/updateNameType")
    public ResponseResult<Object> updateNameType(@CurrentUser User user, int nameType){
        if(user==null){
            return Response.makeErrRsp("参数异常");
        }
        user.setNameType(nameType);
        boolean update = userService.updateById(user);
        if(update){
            String key = "kefu_"+user.getUserId();
            UserManager.getManager().cacheKefuUser(key,user);
        }
        return Response.makeOKRsp("修改成功").setData(user);
    }

    @RequireLogin
    @PostMapping("/updateAvatarShow")
    public ResponseResult<Object> updateAvatarShow(@CurrentUser User user, int avatarShow){
        if(user==null){
            return Response.makeErrRsp("参数异常");
        }
        user.setAvatarShow(avatarShow);
        boolean update = userService.updateById(user);
        if(update){
            String key = "kefu_"+user.getUserId();
            UserManager.getManager().cacheKefuUser(key,user);
        }
        return Response.makeOKRsp("修改成功").setData(user);
    }

    /**
     * 拉黑
     *
     * @author aaa
     * @date 2023-04-12
     */
    @RequireLogin
    @GetMapping("/doBlack")
    public ResponseResult<Object> doBlack(@CurrentUser User user,String userId,int status){
        User clientUser = userService.getUserByUserId(userId);
        if (clientUser == null) return Response.makeOKRsp("操作失败");
        if (user.getUserId().equals(clientUser.getKefuId())){

            userService.doBlackByUserIdAndIp(userId,status);
            //更新会话
            conversationsService.updateIsBlack(status,user.getUserId(),userId);
            if (status == 2){
                UserManager.getManager().addUserBlack(userId);
                RespBody body = new RespBody();
                body.setCommand(Command.COMMAND_ADD_BLACK_RESP);
                body.setData(userId);
                body.setMsg("您已被拉黑");
                ImPacket chatPacket = new ImPacket(Command.COMMAND_ADD_BLACK_RESP,body.toByte());
                JimServerAPI.sendToUser(userId,chatPacket);
                String token = getUserToken(clientUser.getUserId());
                if (token != null){
                    try {
                        JedisTemplate.me().delKey(token);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }else {
                UserManager.getManager().removeUserBlack(userId);
            }
            Conversations byId = conversationsService.selectByUser(user.getUserId(),userId);
            if (byId != null){
                ConversationManager.getManager().sendUserChange(byId);
            }
            return Response.makeOKRsp("拉黑成功");
        }
        return Response.makeOKRsp("操作失败");
    }

    private String getUserToken(String userId){
        List<ImChannelContext> channelContexts = JimServerAPI.getByUserId(userId);
        for (ImChannelContext channelContext: channelContexts) {
            org.jim.core.packets.User user = channelContext.getSessionContext().getImClientNode().getUser();
            return user.getToken();
        }
        return null;
    }

}
